package com.ryan.ohos.extension.event.impl;

import com.ryan.ohos.extension.event.interfaces.View;
import ohos.agp.components.Component;
import ohos.multimodalinput.event.TouchEvent;

/**
 * {@link View}的实现类，所有实现逻辑均转发至此类。
 */
public class ViewHelper {

    private final Component component;
    private boolean consumed;

    public ViewHelper(Component component) {
        this.component = component;
    }

    public boolean dispatchTouchEvent(TouchEvent event) {
        boolean result = false;

        final int action = event.getAction();
        if (action == TouchEvent.PRIMARY_POINT_DOWN) {
            // Defensive cleanup for new gesture
            stopNestedScroll();
            consumed = false;
        }

        if (onTouchEvent(event)) {
            consumed = true;
            result = true;
        } else {
            consumed = false;
        }

        // Clean up after nested scrolls if this is the end of a gesture;
        // also cancel it if we tried an ACTION_DOWN but we didn't want the rest
        // of the gesture.
        if (action == TouchEvent.PRIMARY_POINT_UP ||
                action == TouchEvent.CANCEL ||
                (action == TouchEvent.PRIMARY_POINT_DOWN && !result)) {
            stopNestedScroll();
        }

        return result;
    }

    public boolean onTouchEvent(TouchEvent event) {
        if (component instanceof View) return ((View) component).onTouchEvent(event);
        return false;
    }

    public boolean isConsumed() {
        boolean result = consumed;
        consumed = false;
        return result;
    }

    private void stopNestedScroll() {}
}
